/**
 * 设备播放音频 子线程
 */

import { parentPort } from 'worker_threads';
import Speaker from 'speaker';

const buffers = [];

function createSpeaker() {
    return new Speaker({
        channels: 1,
        bitDepth: 16,
        sampleRate: 32000,
    });
}

parentPort.on('message', (buffer) => {
    buffers.push(buffer);
});

function checkPlaying() {
    if (buffers.length > 0) {
        const buffer = buffers.shift();
        const speaker = createSpeaker();
        speaker.write(buffer);
        speaker.end();
        speaker.once('close', () => {
            checkPlaying();
        });
    }
    setTimeout(() => {
        checkPlaying();
    }, 100);
}

checkPlaying();